<script setup lang="ts">
import {computed, ref, watch} from "vue";
import {
  UserOutlined,
  PlusOutlined,
  CloseCircleOutlined,
  SlackOutlined,
  CaretRightOutlined,
  LockOutlined, createFromIconfontCN
} from "@ant-design/icons-vue";
import AvatarCropper from "@/components/avatarCropper/index.vue"
import {useSystemDictStore} from "@/store/system/systemDictStore";
import {editUser, replyBlogLink} from "@/api/user/user";
import {ECode, iconFontAddress} from "@/util/commonUtil";
import {message} from "ant-design-vue";
import {useAppConfigStore} from "@/store/system/appConfigStore";
import PasswordEdit from "./item/passwordEdit.vue"
import CommentPaneList from "./item/commentPaneList.vue"
import {getCommentListByUser} from "@/api/comment/comment";

const props = defineProps({
  drawerShow: {
    type: Boolean,
    default: () => false
  },
  user: {
    type: Object,
    default: () => {
    }
  },
  userAmount: {
    type: Number,
    default: () => 0
  }
});
const emit = defineEmits(['closeDrawer']);
const show = ref<boolean>(props.drawerShow);
const userInfo = ref<any>(props.user);
const photoUrl = ref<string>(import.meta.env.VITE_PICTURE_API + '/file/cropperPicture');
const imageCropperKey = ref<number>(0);
const imageCropperShow = ref<boolean>(false);
const activeKey = ref<string>('1');
const activeCollapseKey = ref<string[]>(['1']);
const customStyle = 'background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden';
const genderDictList: any = computed(() => useSystemDictStore().SysUserSex)
const yesNoDictList: any = computed(() => useSystemDictStore().SysYesNo)
const editorModalDictList: any = computed(() => useSystemDictStore().SysEditorModal)
const webSiteConfig: any = computed(() => useAppConfigStore().getWebConfigData)
// 友链申请
const blogLink = ref<any>({
  avatar: '',
  title: '',
  summary: '',
  url: '',
  email: '',
  fileUid: '',
  photoList: []
})
const info = ref<any>(webSiteConfig.value || {})
// 引入阿里图标库
const IconFont = createFromIconfontCN({
  scriptUrl: iconFontAddress,
})
// 表单设置
const labelCol = {style: {width: '80px'}}
const wrapperCol = {span: 14}
// 分页设置
const currentPage = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)
const isEnd = ref<boolean>(false)
const commentListByPane = ref<any>([])
watch(() => props.user, (val: any) => {
  userInfo.value = val;
})
watch(() => props.drawerShow, (val: boolean) => {
  show.value = val;
})

function changeTab(e: any) {
  switch (e) {
    case '4': {
      getCommentList(true)
    }
      break
  }
}

async function getCommentList(isClean: boolean) {
  if (isClean) {
    commentListByPane.value = [];
  }
  let params: any = {};
  params.pageSize = pageSize.value;
  params.currentPage = currentPage.value;
  await getCommentListByUser(params).then((response: any) => {
    if (response.code === ECode.SUCCESS && response.data.records.length > 0) {
      let commentList = response.data.records;
      commentListByPane.value = commentListByPane.value.concat(commentList);
      total.value = response.data.total;
      pageSize.value = response.data.size;
      currentPage.value = response.data.current;
      // 全部加载完毕
      if (commentList.length < pageSize.value) {
        isEnd.value = true;
      }
    } else {
      isEnd.value = true;
    }
  })
}

function changePage(e: number) {
  currentPage.value = e;
  getCommentList(true)
}

function drawerEmit(e: boolean) {
  emit('closeDrawer', e);
}

function imageCropperShowClose() {
  imageCropperShow.value = false;
  drawerEmit(true)
}

function imageCropperShowOpen() {
  imageCropperShow.value = true;
  drawerEmit(false)
}

function cropSuccess(resData: any) {
  imageCropperShow.value = false
  imageCropperKey.value = imageCropperKey.value + 1
  if (activeKey.value === '1') {
    // 激活个人中心页面
    userInfo.value.photoUrl = resData.url;
    userInfo.value.avatar = resData.uid;
  }
  if (activeKey.value === '2') {
    // 激活友链申请页面
    let photoList = [];
    photoList.push(resData.url);
    blogLink.value.photoList = photoList;
    blogLink.value.fileUid = resData.uid;
  }
  drawerEmit(true)
}

function deletePhoto(type: string) {
  switch (type) {
    case 'user': {
      userInfo.value.photoUrl = '';
      userInfo.value.avatar = '';
    }
      break;
    case "link": {
      blogLink.value.photoList = null;
    }
      break;
  }
}

function editUserMethod() {
  if (userInfo.value.nickName.length === 0) {
    message.warning('昵称不能为空')
    return
  }
  if (userInfo.value.nickName.length > 20) {
    message.warning('昵称长度不能超过20')
    return
  }
  if (userInfo.value.email.length > 0) {
    if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(userInfo.value.email)) {
      message.warning('请输入正确的邮箱')
      return
    }
  }
  editUser(userInfo.value).then((response: any) => {
    if (response.code === ECode.SUCCESS) {
      message.success(response.data)
    } else {
      message.error(response.message)
    }
  })
}

function replyBlogLinkMethod() {
  if (blogLink.value.title.length === 0) {
    message.warning('友链名称不能为空')
    return
  }
  if (blogLink.value.summary.length === 0) {
    message.warning('网站简介不能为空')
    return
  }
  if (blogLink.value.url.length === 0) {
    message.warning('网站地址不能为空')
    return
  }
  if (blogLink.value.email.length === 0) {
    message.warning('站长邮箱不能为空')
    return
  }
  if (blogLink.value.email.length > 0) {
    if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(blogLink.value.email)) {
      message.warning('请输入正确的邮箱')
      return
    }
  }
  replyBlogLink(blogLink.value).then((response: any) => {
    if (response.code === ECode.SUCCESS) {
      message.success(response.data)
    } else {
      message.error(response.message)
    }
  })
}

function submitForm(type: string) {
  switch (type) {
    case 'editUser': {
      // 提交用户信息
      editUserMethod()
    }
      break;
    case "replyBlogLink": {
      replyBlogLinkMethod()
    }
      break;
  }
}
</script>

<template>
  <section class="headerDrawer">
    <a-drawer
        v-model:open="show"
        @close="drawerEmit(false)"
        size="large"
        title="系统面板"
        placement="right">
      <a-tabs tabPosition="left" v-model:activeKey="activeKey" @change="changeTab">
        <a-tab-pane key="1">
          <template #tab>
            <UserOutlined class="text-base"/>
            <span>个人中心</span>
          </template>
          <a-form :model="userInfo"
                  layout="horizontal"
                  class="max-w-[600px]"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol">
            <a-form-item label="头像" name="photoUrl">
              <div class="relative w-24 h-24 cursor-pointer">
                <CloseCircleOutlined class="absolute top-1 right-1 text-white" @click="deletePhoto('user')"/>
                <img v-if="userInfo.photoUrl" :src="userInfo.photoUrl" alt="avatar" class="pointer-events-none rounded">
                <div
                    class="userAvatarUpload relative w-24 h-24 cursor-pointer flex flex-col justify-center items-center rounded"
                    v-else
                    @click="imageCropperShowOpen">
                  <plus-outlined></plus-outlined>
                  <div class="ant-upload-text">上传头像</div>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="昵称" name="nickName"
                         :rules="[{ required: true, message: '请输入用户昵称!' }]">
              <a-input v-model:value.trim="userInfo.nickName" placeholder="请输入用户昵称"/>
            </a-form-item>
            <a-form-item label="性别"
                         :rules="[{ required: true, message: '请选择性别!' }]">
              <a-radio-group v-model:value="userInfo.gender">
                <template v-for="gender in genderDictList" :key="gender.uid">
                  <a-radio :value="gender.dictValue">{{ gender.dictLabel }}</a-radio>
                </template>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="钱包">
              <span class="text-rose-500 font-semibold mr-2">{{ userAmount }}</span>元
            </a-form-item>
            <a-form-item label="邮件通知" :rules="[{ required: true, message: '请选择邮件通知!' }]">
              <a-radio-group v-model:value="userInfo.startEmailNotification">
                <template v-for="item in yesNoDictList" :key="item.uid">
                  <a-radio :value="parseInt(item.dictValue)">{{ item.dictLabel }}</a-radio>
                </template>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="编辑器" :rules="[{ required: true, message: '请选择编辑器!' }]">
              <a-radio-group v-model:value="userInfo.editorModel">
                <template v-for="item in editorModalDictList" :key="item.uid">
                  <a-radio :value="item.dictValue">{{ item.dictLabel }}</a-radio>
                </template>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="userInfo.email" placeholder="请输入邮箱"/>
            </a-form-item>
            <a-form-item label="职业" name="occupation">
              <a-input v-model:value="userInfo.occupation" placeholder="请输入职业"/>
            </a-form-item>
            <a-form-item label="简介" name="summary">
              <a-textarea :rows="4" v-model:value="userInfo.summary" placeholder="请输入个人简介"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
              <a-button html-type="submit" type="primary" @click="submitForm('editUser')">保存</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2">
          <template #tab>
            <SlackOutlined class="text-base"/>
            <span>友链申请</span>
          </template>
          <a-form :model="blogLink"
                  layout="horizontal"
                  class="max-w-[600px]"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol">
            <a-collapse
                v-model:activeKey="activeCollapseKey"
                :bordered="false"
                style="background: rgb(255, 255, 255)"
            >
              <template #expandIcon="{ isActive }">
                <CaretRightOutlined :rotate="isActive ? 90 : 0"/>
              </template>
              <a-collapse-panel key="1" header="友链申请需知☘️" :style="customStyle">
                <div v-highlight v-html="info.linkApplyTemplate"/>
              </a-collapse-panel>
              <a-collapse-panel key="2" header="本站信息🎉" :style="customStyle">
                <div class="webSiteInfo flex flex-col gap-4">
                  <div class="flex items-center gap-2">
                    <span class="text-[14px]">网站名称:</span>
                    <span class="text-[14px] text-blue-500">
                      {{ info.title }}
                    </span>
                  </div>
                  <div class="flex items-center gap-2">
                    <span class="text-[14px]">网站博主:</span>
                    <span class="text-[14px] text-blue-500">{{ info.author }}</span>
                  </div>
                  <div class="flex items-center gap-2">
                    <span class="text-[14px]">网站图标:</span>
                    <a-tooltip>
                      <template #title>
                        <span class="text-[12px]">{{ info.logoPhoto }}</span>
                      </template>
                      <span class="text-[14px] text-rose-500 cursor-pointer">网站图标地址</span>
                    </a-tooltip>
                  </div>
                  <div class="flex items-center gap-2">
                    <span class="text-[14px]">网站简介:</span>
                    <a-tooltip trigger="click">
                      <template #title>
                        <span class="text-[12px]">{{ info.summary }}</span>
                      </template>
                      <span class="text-[14px] text-rose-500 cursor-pointer">点击查看</span>
                    </a-tooltip>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
            <a-divider>
              <span class="text-[14px] text-gray-300">✨友链申请表✨</span>
            </a-divider>
            <a-form-item label="网站图标" name="avatar">
              <div class="relative w-24 h-24 cursor-pointer">
                <CloseCircleOutlined class="absolute top-1 right-1 text-white" @click="deletePhoto('link')"/>
                <img v-if="blogLink.avatar" :src="blogLink.avatar" alt="avatar" class="pointer-events-none rounded">
                <div
                    class="userAvatarUpload relative w-24 h-24 cursor-pointer flex flex-col justify-center items-center rounded"
                    v-else
                    @click="imageCropperShowOpen">
                  <plus-outlined></plus-outlined>
                  <div class="ant-upload-text">上传网站图标</div>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="友链名称" name="title"
                         :rules="[{ required: true, message: '请输入友链名称!' }]">
              <a-input v-model:value.trim="blogLink.title" placeholder="请输入友链名称"/>
            </a-form-item>
            <a-form-item label="网站简介" name="summary"
                         :rules="[{ required: true, message: '请输入网站简介!' },
                         {min: 2,max: 50, message: '网站简介最多输入50个字符'}]">
              <a-input v-model:value.trim="blogLink.summary" placeholder="请输入网站简介"/>
            </a-form-item>
            <a-form-item label="网站地址" name="url"
                         :rules="[{ required: true, message: '请输入网站地址!' },
                         {max: 255, message: '网站地址最多输入255个字符'}]">
              <a-input v-model:value.trim="blogLink.url" placeholder="请输入网站地址"/>
            </a-form-item>
            <a-form-item label="订阅地址" name="rss">
              <a-input v-model:value.trim="blogLink.rss" placeholder="请输入订阅地址"/>
            </a-form-item>
            <a-form-item label="站长邮箱" name="email"
                         :rules="[{ required: true, message: '请输入站长邮箱!' }]">
              <a-input v-model:value.trim="blogLink.email" placeholder="用于申请通过邮件通知"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
              <a-button html-type="submit" type="primary" @click="submitForm('replyBlogLink')">提交申请</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="3">
          <template #tab>
            <LockOutlined class="text-base"/>
            <span>修改密码</span>
          </template>
          <PasswordEdit :userInfo="userInfo"/>
        </a-tab-pane>
        <a-tab-pane key="4">
          <template #tab>
            <IconFont type="icon-pinglun" class="text-base"/>
            <span>我的评论</span>
          </template>
          <CommentPaneList
              :comment-list="commentListByPane"
              :currentPage="currentPage"
              :pageSize="pageSize"
              :total="total"
              :isEnd="isEnd"
              @changePage="changePage"/>
        </a-tab-pane>
      </a-tabs>
    </a-drawer>
    <!-- 头像裁剪 -->
    <AvatarCropper
        v-show="imageCropperShow"
        :key="imageCropperKey"
        :url="photoUrl"
        :width="300"
        :height="300"
        lang-type="zh"
        @close="imageCropperShowClose"
        @crop-upload-success="cropSuccess"/>
  </section>
</template>

<style scoped lang="less">
.userAvatarUpload {
  background-color: rgba(0, 0, 0, 0.02);
  border: 1px dashed #d9d9d9;
}

.userAvatarUpload:hover .ant-upload-text {
  color: rgba(232, 35, 35, 0.7);
}
</style>
